<template>
  <div>
    <el-upload
      action="#"
      :file-list="fileList"
      list-type="picture-card"
      :class="{disable:fileList.length===1}"
      :on-preview="preview"
      :on-remove="onRemove"
      :on-change="onChange"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showProgress" :percentage="percent" style="width:146px" :show-text="false" />
    <el-dialog title="预览" :visible="showDialog" @close="showDialog=false">
      <el-row type="flex" justify="center">
        <img :src="imgUrl" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// 创建实例
const cos = new COS({
  // 验证身份
  SecretId: 'AKIDFJ6crpWw5xYrte8LHwPbV8VaOvB9qGTP',
  SecretKey: 'g5C2bttd6IDtIPFo67qITNzKPDk0y44o'
})
export default {
  data() {
    return {
      showProgress: false,
      percent: 0,
      fileList: [],
      showDialog: false,
      imgUrl: ''
    }
  },
  methods: {
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    onRemove(file, fileList) {
      // 每次删除都拿到最新数据数组
      // 手动复制改变即可
      this.fileList = [...fileList]
    },
    onChange(file, fileList) {
      this.fileList = [...fileList]
    },
    beforeUpload(file) {
      console.log(file)
      // 校验大小
      const maxSize = 500 * 1024
      if (file.size > maxSize) {
        this.$message.warning('文件大小不能超500k')
        return false
      }
      // 校验类型
      const whiteList = ['image/jpeg', 'image/png']
      if (!whiteList.includes(file.type)) {
        this.$message.warning('目前只允许jpeg/png图片')
        return false
      }
    },
    upload(params) {
      console.log('开始上传')
      console.log(params.file)
      this.showProgress = true
      cos.putObject({
        // 储存桶名称
        Bucket: 'hr64-1306795502', /* 必须 */
        // 地区代号
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        // 想要的文件名
        Key: params.file.name,
        // 标准的储存固定写法
        StorageClass: 'STANDARD',
        // 文件对象本身
        Body: params.file, // 上传文件对象
        // 每当进度发生变化时触发
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        // 上传结束回调
        console.log(err || data)
        if (!err) {
          // 成功回调逻辑
          console.log('上传完毕')
          this.fileList[0].url = 'http://' + data.Location
          // 手动告诉上传组件,这张图片已经上传成功
          this.fileList[0].status = 'success'
        }
        setTimeout(() => {
          this.showProgress = false
        }, 800)
      })
    }
  }
}
</script>

<style lang="scss" scoped >
 .disable{
     ::v-deep .el-upload--picture-card{
         display: none;
     }
 }
</style>>

